/*
 * @Author: wangjq4214
 * @Date: 2022-05-03 22:42:37
 * @LastEditTime: 2022-05-08 17:27:26
 * @LastEditors: wangjq4214
 */
import {
  Form,
  Select,
  Button,
  InputNumber,
  FormInstance,
} from '@arco-design/web-react';
import { post } from '@/apis';
import { COMPUTE_ADD_URL } from '@/apis/compute';
import { loadingAtom, stepAtom } from '../model';

const FormItem = Form.Item;
const Option = Select.Option;

const NewForm = () => {
  const formRef = useRef<FormInstance<{
    computeType: number;
    computeScale: number;
    mainNodeCPU: number;
    slaveNodeCPU: number;
  }> | null>();
  const setLoading = useSetAtom(loadingAtom);
  const setStep = useSetAtom(stepAtom);

  const handleStorageTypeChange = () => {
    formRef.current?.setFields({
      mainNodeCPU: { value: 8 },
      slaveNodeCPU: { value: 8 },
    });
  };

  const handleSubmit = () => {
    setLoading(true);
    const data = formRef.current?.getFieldsValue();

    post(COMPUTE_ADD_URL, {
      ComputeType: data?.computeType,
      ComputeScale: data?.computeScale,
      mainNodeMemory: data?.mainNodeCPU,
      slaveNodeMemory: data?.slaveNodeCPU,
    })
      .then(() => {
        setStep('submit');
      })
      .catch((e) => {
        console.log(e);
      })
      .finally(() => setLoading(false));
  };

  return (
    <Form
      ref={(e) => {
        formRef.current = e;
      }}
      className="w-550px"
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 18 }}
      onSubmit={handleSubmit}
      initialValues={{
        computeType: 1,
        computeScale: 1,
        mainNodeCPU: 8,
        slaveNodeCPU: 8,
      }}
    >
      <FormItem field="computeType" label="计算类型" required>
        <Select onChange={handleStorageTypeChange}>
          <Option value={1}>MapReduce</Option>
          <Option value={2}>MPI</Option>
        </Select>
      </FormItem>

      <FormItem field="computeScale" label="集群大小" required>
        <Select>
          <Option value={1}>小</Option>
          <Option value={2}>中</Option>
          <Option value={3}>大</Option>
        </Select>
      </FormItem>

      <FormItem field="mainNodeCPU" label="主节点核数(个)" required>
        <InputNumber min={8} />
      </FormItem>

      <FormItem field="slaveNodeCPU" label="从节点核数(个)" required>
        <InputNumber min={8} />
      </FormItem>

      <FormItem
        wrapperCol={{
          offset: 6,
        }}
      >
        <Button type="primary" htmlType="submit">
          提交
        </Button>
      </FormItem>
    </Form>
  );
};

export default NewForm;
